import json

from django.contrib.auth import login, authenticate, logout
from celery_tasks.email.tasks import send_verify_email
from django.shortcuts import render, redirect
from django.views import View
from django import http
from django.db import DatabaseError
from django.urls import reverse
from django.contrib.auth.mixins import LoginRequiredMixin

import re
from django_redis import get_redis_connection
import logging

from .models import User, Address
from meiduo_mall.utils.views import LoginRequiredJSONMixin
from .utils import generate_verify_email_url
from meiduo_mall.apps.goods.models import SKU

# Create your views here.
# 创建日志输出器
logger = logging.getLogger('collect')


class RegisterView(View):
    """用户注册"""

    # 前端向后端索取数据 GET
    # 前端向后端发送隐私数据 POST
    # 修改后端数据 PUT
    def get(self, request, *args, **kwargs):
        return render(request, 'register.html')

    def post(self, request, *args, **kwargs):
        """实现用户注册业务逻辑"""
        # 接收参数，表单参数
        username = request.POST['username']
        password = request.POST.get('password')
        password2 = request.POST.get('password2')
        mobile = request.POST.get('mobile')
        sms_code = request.POST.get('sms_code')
        allow = request.POST.get('allow')
        print(username)
        """校验参数"""
        # 判断参数是否齐全 all([])校验列表中的元素是否为空
        if not all([username, password, password2, mobile, allow]):
            return http.HttpResponseForbidden('缺少必传的参数')
        # 判断用户名是否是5-20个字符
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return http.HttpResponseForbidden('请输入5-20个字符')
        # 判断密码是否是8-20个字符
        if len(password) < 8 or len(password) > 20:
            return http.HttpResponseForbidden('请输入8-20位密码')
        # 判断两次密码是否一致
        if password != password2:
            return http.HttpResponseForbidden('输入的两次密码不一致')
        # 判断手机号是否合法
        if not re.match(r'^1[345789]\d{9}$', mobile):
            return http.HttpResponseForbidden('请输入正确的手机号')

        """判断短信验证码是否正确"""
        # 获取数据库保存的验证码
        redis_conn = get_redis_connection('image_code')
        mobileCode = redis_conn.get('sms_%s' % mobile)
        # 校验验证码
        mobileCode = mobileCode.decode()
        if mobileCode != sms_code:
            return http.HttpResponseForbidden("请输入正确的验证码")
        # 响应
        # 判断是否勾选用户协议
        if allow != 'on':
            return http.HttpResponseForbidden('请勾选用户协议')
        """保存注册数据"""
        try:
            user = User.objects.create_user(username=username, password=password, mobile=mobile)
        except DatabaseError:
            return render(request, 'register.html', {'register_error': "注册失败"})

        """实现状态保持"""
        # django自带的用户认证系统  from django.contrib.auth import login
        login(request, user)

        """将用户名保存到cookie"""
        response = redirect(reverse('index:index'))
        response.set_cookie('username', user.username, max_age=3600 * 24 * 15)

        """响应结果"""
        # return http.HttpResponse('注册成功，重定向到首页')
        # return redirect('/')
        return response


class UsernameCountView(View):
    """判断用户名是否重复"""

    def get(self, request, username):
        """
        :param request:
        :param username: 用户名
        :return:  JSON
        """
        # 接收和校验参数
        # 路由校验参数，错误返回404
        # filter() 返回满足条件的结果集
        count = User.objects.filter(username=username).count()
        return http.JsonResponse({
            'code': '0',
            'errmsg': 'OK',
            'count': count
        })


class MobileCountView(View):
    """判断手机号是否重复"""

    def get(self, request, mobile):
        """
        :param request:
        :param mobile:  手机号
        :return: JSON
        """
        # 接收和校验参数
        # 路由校验参数，错误返回404
        # filter() 返回满足条件的结果集
        count = User.objects.filter(mobile=mobile).count()
        return http.JsonResponse({
            'code': '0',
            'errmsg': 'OK',
            'count': count
        })


class LoginView(View):
    """用户登录"""

    def get(self, request):
        """提供用户登录界面"""
        return render(request, 'login.html')

    def post(self, request):
        """用户登录逻辑"""
        # 接收参数
        username = request.POST.get('username')
        password = request.POST.get('password')
        remember = request.POST.get('remember')
        print(remember)
        # 校验参数
        if not all([username, password]):
            return http.HttpResponseForbidden("缺少必传的参数")
        # 判断用户名是否是5-20个字符
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return http.HttpResponseForbidden('请输入正确的用户名或密码')
        # 判断密码是否是8-20个字符
        if len(password) < 8 or len(password) > 20:
            return http.HttpResponseForbidden('请输入8-20位密码')
        # 从数据库取出数据
        # user = User.objects.get(username=username)
        # user.check_password()
        user = authenticate(username=username, password=password)
        print(user)
        if user is None:
            return render(request, 'login.html', {'account_error': "账户或密码错误"})

        # 状态保持
        login(request, user)
        # 使用remember查看是否状态保持
        if remember != 'on':
            # 没有记住登录，状态保持会在浏览器会话结束后销毁
            request.session.set_expiry(0)
        else:
            # 状态保持为两周  (默认是两周)
            request.session.set_expiry(None)

        next = request.GET.get('next')
        if next:
            # 重定向到next
            response = redirect(next)
        else:
            # 重定向到首页
            response = redirect(reverse('index:index'))
        """用户名缓存到cookie中，展示在首页"""
        response.set_cookie('username', user.username, max_age=3600 * 24 * 15)

        # 响应结果
        return response


class LogoutView(View):
    """用户退出登陆"""

    def get(self, request):
        """用户退出登陆逻辑实现"""
        # 清除状态保持信息
        logout(request)
        # 退出登陆后重定向到首页
        response = redirect(reverse('index:index'))
        # 清除cookie信息
        response.delete_cookie('username')
        # 响应
        return response


# LoginRequiredMixin如果用户未登录则跳转
class UserInfoView(LoginRequiredMixin, View):
    """用户中心"""

    def get(self, request):
        """提供用户中心页面"""
        # if request.user.is_authenticated:
        #     return render(request, 'user_center_info.html')
        # else:
        #     return redirect(reverse('users:login'))

        # 如果LoginRequiredMixin判断出用户已经登录，那么request.user就是登录用户对象
        context = {
            'username': request.user.username,
            'mobile': request.user.mobile,
            'email': request.user.email,
            'email_active': request.user.email_active
        }
        return render(request, 'user_center_info.html', context)


class EmailView(LoginRequiredJSONMixin, View):
    """添加邮箱"""

    # 更新字段，使用put请求
    def put(self, request):
        """添加邮箱的后端逻辑"""
        # 接收参数
        email_str = request.body.decode()
        email_dict = json.loads(email_str)
        email = email_dict.get('email')
        # 校验参数
        if not email:
            return http.HttpResponseForbidden('缺少email参数')
        if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
            return http.HttpResponseForbidden('参数email有误')
        # 赋值email字段
        try:
            request.user.email = email
            request.user.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': '4001', 'errmsg': '添加邮箱失败'})
        # 发送邮箱验证邮件
        verify_url = generate_verify_email_url(request.user)
        send_verify_email.delay(email, verify_url=verify_url)
        # 响应添加邮箱结果
        return http.JsonResponse({'code': '0', 'errmsg': '添加邮箱成功'})


class VerifyEmailView(View):
    """验证邮箱激活链接"""

    def get(self, request):
        """
        主体逻辑
        :param request:
        :return:
        """
        pass


class AdderssView(LoginRequiredMixin, View):
    """用户收货地址"""

    def get(self, request):
        """界面展示"""
        # 获取当前的登陆用户
        login_user = request.user
        # 使用当前的登陆用户和is_deleted字段查询地址信息
        addresses = Address.objects.filter(user=login_user, is_deleted=False)
        # 将用户地址模型列表转为字典列表
        # 因为JSONResponse和Vue.js不认识模型列表，只有DjangoheJinja2模板引擎认识
        address_dict_list = []
        for address in addresses:
            address_dict = {
                "id": address.id,
                "title": address.title,
                "receiver": address.receiver,
                "province": address.province.name,
                "city": address.city.name,
                "district": address.district.name,
                "place": address.place,
                "mobile": address.mobile,
                "tel": address.tel,
                "email": address.email
            }
            address_dict_list.append(address_dict)
        context = {
            'default_address_id': login_user.default_address_id,
            'addresses': address_dict_list,
        }
        return render(request, 'user_center_site.html', context)


class CreateAddressView(LoginRequiredJSONMixin, View):
    """新增地址"""

    def post(self, request):
        """新增地址的逻辑实现"""
        # print(request.body.decode())
        # 接收参数
        json_str = request.body.decode()
        json_dict = json.loads(json_str)
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')

        # 校验参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return http.HttpResponseForbidden('缺少必传参数')
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.HttpResponseForbidden('参数mobile有误')
        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return http.HttpResponseForbidden('参数tel有误')
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return http.HttpResponseForbidden('参数email有误')

        """实现新增地址逻辑"""
        # 判断是否超过地址上限：最多20个
        # Address.objects.filter(user=request.user).count()
        count = request.user.addresses.count()
        if count >= 20:
            return http.JsonResponse({'code': '4101', 'errmsg': '超过地址数量上限'})

        # 保存地址信息
        try:
            address = Address.objects.create(
                user=request.user,
                title=receiver,
                receiver=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email
            )

            # 设置默认地址
            if not request.user.default_address:
                request.user.default_address = address
                request.user.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': '4001', 'errmsg': '新增地址失败'})

        # 新增地址成功，将新增的地址响应给前端实现局部刷新
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }
        print(address_dict)
        # 响应保存结果
        return http.JsonResponse({'code': '0', 'errmsg': '新增地址成功', 'address': address_dict})


class UpdateDestroyAddressView(LoginRequiredJSONMixin, View):
    """修改和删除地址"""

    def put(self, request, address_id):
        """修改地址"""
        # 接收参数
        json_dict = json.loads(request.body.decode())
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')

        # 校验参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return http.HttpResponseForbidden('缺少必传参数')
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.HttpResponseForbidden('参数mobile有误')
        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return http.HttpResponseForbidden('参数tel有误')
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return http.HttpResponseForbidden('参数email有误')

        # 判断地址是否存在,并更新地址信息
        try:
            Address.objects.filter(id=address_id).update(
                user=request.user,
                title=receiver,
                receiver=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email
            )
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': '4010', 'errmsg': '更新地址失败'})

        # 构造响应数据
        address = Address.objects.get(id=address_id)
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }

        # 响应更新地址结果
        return http.JsonResponse({'code': '0', 'errmsg': '更新地址成功', 'address': address_dict})

    def delete(self, request, address_id):
        """删除地址"""
        try:
            # 查询要删除的地址
            address = Address.objects.get(id=address_id)

            # 将地址逻辑删除设置为True
            address.is_deleted = True
            address.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': '4010', 'errmsg': '删除地址失败'})

        # 响应删除地址结果
        return http.JsonResponse({'code': '0', 'errmsg': '删除地址成功'})


class DefaultAddressView(LoginRequiredJSONMixin, View):
    """设置默认地址"""

    def put(self, request, address_id):
        """设置默认地址"""
        try:
            # 接收参数,查询地址
            address = Address.objects.get(id=address_id)

            # 设置地址为默认地址
            request.user.default_address = address
            request.user.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': '4010', 'errmsg': '设置默认地址失败'})

        # 响应设置默认地址结果
        return http.JsonResponse({'code': '0', 'errmsg': '设置默认地址成功'})


class UpdateTitleAddressView(LoginRequiredJSONMixin, View):
    """修改标题"""
    def put(self, request, address_id):
        # 接收参数
        title_dict = json.loads(request.body.decode())
        title = title_dict.get('title')
        # 校验参数
        if not title:
            return http.HttpResponseForbidden("缺少必传的参数")
        # 查询 赋值并保存
        try:
            address = Address.objects.get(id=address_id)
            address.title = title
            address.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({
                'code': '4010',
                'errmsg': '更新标题失败'
            })
        return http.JsonResponse({
            'code': '0',
            'errmsg': '更新成功'
        })


class ChangePasswordView(LoginRequiredMixin, View):
    """修改密码"""
    def get(self, request):
        """界面展示"""
        return render(request, 'user_center_pass.html')

    def post(self, request):
        """修改密码后端逻辑"""
        # 接收参数(表单数据， post请求)
        old_password = request.POST.get('old_password')
        new_password = request.POST.get('new_password')
        new_password2 = request.POST.get('new_password2')
        # 校验参数
        if not all([old_password, new_password, new_password2]):
            return http.HttpResponseForbidden("缺少必传参数")

        if not request.user.check_password(old_password):
            return render(request, 'user_center_pass.html', {'origin_pwd_errmsg': '原始密码错误'})

        if not re.match(r'^[0-9A-Za-z]{8,20}$', new_password):
            return http.HttpResponseForbidden('密码最少8位，最长20位')
        if new_password != new_password2:
            return http.HttpResponseForbidden('两次输入的密码不一致')
        # 修改密码
        try:
            request.user.set_password(new_password)
            request.user.save()
        except Exception as e:
            logger.error(e)
            return render(request, 'user_center_pass.html', {'origin_pwd_errmsg': '修改密码失败'})

        # 清理状态保持信息
        logout(request)
        response = redirect(reverse('users:login'))
        response.delete_cookie('username')

        # 响应密码修改结果：重定向到登录界面
        return response


class UserBrowseHistory(LoginRequiredJSONMixin, View):
    """用户浏览记录"""
    def post(self, request):
        # 接收参数
        print(111)
        json_str = request.body.decode()
        json_dict = json.loads(json_str)
        sku_id = json_dict.get('sku_id')
        # 校验参数
        try:
            sku = SKU.objects.get(id=sku_id)
        except Exception as e:
            return http.HttpResponseForbidden('缺少参数')

        # 保存用户浏览数据
        redis_conn = get_redis_connection('history')
        pl = redis_conn.pipeline()
        user_id = request.user.id

        # 先去重
        pl.lrem('history_%s' % user_id, 0, sku_id)
        # 再存储，最近浏览的商品在最前面，使用lpush
        pl.lpush('history_%s' % user_id, sku_id)
        # 最后截取
        pl.ltrim('history_%s' % user_id, 0, 4)
        # 执行管道
        pl.execute()

        # 响应结果
        return http.JsonResponse({'code': '0', 'errmsg': 'OK'})

    def get(self, request):
        # 获取redis中存储的商品id
        redis_conn = get_redis_connection('history')
        sku_ids = redis_conn.lrange('history_%s' % request.user.id, 0, -1)

        """
        {
            "code":"0",
            "errmsg":"OK",
            "skus":[
                {
                    "id":6,
                    "name":"Apple iPhone 8 Plus (A1864) 256GB 深空灰色 移动联通电信4G手机",
                    "default_image_url":"http://image.meiduo.site:8888/group1/M00/00/02/CtM3BVrRbI2ARekNAAFZsBqChgk3141998",
                    "price":"7988.00"
                },
                ......
            ]
        }
        """
        # 遍历sku_ids
        skus = []
        for sku_id in sku_ids:
            # 在数据库查询数据
            sku = SKU.objects.get(id=sku_id)
            skus.append({
                'id': sku.id,
                'name': sku.name,
                'default_image_url': sku.default_image.url,
                'price': sku.price
            })
        return http.JsonResponse({
            'code': '0',
            'errmsg': 'OK',
            'skus': skus
        })

